import {React,Fragment,useState,useEffect,useRef} from 'react';
import moment from 'moment';
import {Table,Button,Space,Input,Modal,Select,DatePicker,Radio,message} from 'antd';
import {SearchOutlined,EditOutlined,DeleteOutlined,ArrowUpOutlined} from '@ant-design/icons';
import {inject,observer} from 'mobx-react';
import './css/CustomerInfo.css';

const {Option} = Select;
const dateFormat = 'YYYY-MM-DD';

// 成功提示框
const success = (value) => {
  message.success(value);
};
// 失败提示
const error = (value) => {
  message.error(value);
};
//列名 
const mapFieldToChinese = {
  id:'序号',
  memberCardNum:'会员卡号',
  memberName:'会员名称',
  memberType:'会员类型',
  totalIntegral:'总积分',
  totalMonetary:'总消费金额(元)',
  birthday:'生日',
  sex:'性别',
  phone:'联系电话',
  idNum:'身份证号',
  openCardStore:'开卡门店',
  openCardDate:'开卡日期'
}
// 复选
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User',
    // Column configuration not to be checked
    name: record.name,
  }),
};

function CustomerInfo(props) {
  const [loading,setLoading] = useState(false)
  // 
      const [id,setId] = useState()//获取序号
      const [cardNum,setCardNum] = useState()//获取卡号
      const searchRef = useRef()//获取查询内容
      // const idRef = useRef();
      const cardNumRef = useRef()//会员卡号
      const memberNameRef = useRef()//会员名称
      const phoneRef = useRef()//联系电话
      const idNumRef = useRef()//身份证号
      const totalIntegralRef = useRef()//总积分
      const totalMonetaryRef = useRef()//总消费金额

      const [memberType,setMemberType] = useState('1')//会员类型
      function vipTypeChange(value) {
        setMemberType(value)
      }

      const [sex, setSex] = useState(0);//性别
      const sexChange = e => {
        console.log('radio checked', e.target.value);
        setSex(e.target.value);
      };

      const [birthday,setBirthday] = useState('')//生日
      function birthdayChange(date, dateString) {
        setBirthday(moment().format('YYYY-MM-DD'));
      }

      const [openCardStore,setOpenCardStore] = useState('望京门店')//开卡门店
      function openCardStoreChange(value) {
        setOpenCardStore(value)
      }

      const [openCardDate,setOpenCardDate] = useState()//开卡日期
      function openCardDateChange(date, dateString) {
        setOpenCardDate(moment().format('YYYY-MM-DD'));
      }

      // 升级对话框状态
      const [upgrade, setUpgrade] = useState(false);
      // 添加xiugai框状态
      const [add, setAdd] = useState(false);
      const [addEdit,setAddEdit]=useState('')//判断是添加还是修改
        // 删除提示模态框
      const [del, setDel] = useState(false);
      // 清空
      function clear(){
        cardNumRef.current.state.value='';
        memberNameRef.current.state.value='';
        phoneRef.current.state.value='';
        idNumRef.current.state.value='';
        totalIntegralRef.current.state.value='';
        totalMonetaryRef.current.state.value='';
        setMemberType('1');
        setOpenCardStore("望京门店")
        setSex(0);
        setBirthday(new Date());
      }
      // 添加修改
      function addEditInfo(fun){
        let values = {
          fun:fun,
          id:id,
          memberCardNum:cardNumRef.current.state.value,
          memberName:memberNameRef.current.state.value,
          memberType:memberType,
          sex:sex,
          birthday:birthday,
          phone:phoneRef.current.state.value,
          idNum:idNumRef.current.state.value,
          totalIntegral:totalIntegralRef.current.state.value,
          totalMonetary:totalMonetaryRef.current.state.value,
          openCardDate:openCardDate,
          openCardStore:openCardStore
        }
        props.CustomerManagement.addEditCustomerInfo(values).then((res)=>{
          if(res.code==200){
            success(res.msg)
          }else{
            error(res.msg)
          }
          getList()
        }).catch((err)=>{
          console.log(err);
        })
          clear();
      }
      // 删除
      function delInfo(){
        let values = {
          id:id
        }
        props.CustomerManagement.delCustomerInfo(values).then((res)=>{
          console.log(res);
          if(res.code==200){
            success(res.msg)
          }
          getList()
        }).catch((err)=>{
          console.log(err);
          error(err.msg)
        })
      } 
      // 会员升级
      function upGrad(){
        let values = {
          id:id,
          memberType:memberType,
          totalIntegral:totalIntegralRef.current.state.value
        }
        props.CustomerManagement.upgrade(values).then((res)=>{
          console.log(res);
          if(res.code==200){
            success(res.msg)
          }
          setMemberType('0');
          totalIntegralRef.current.state.value='';
          getList()
        }).catch((err)=>{
          console.log(err);
          error(err.msg)
        })
      } 
      // 查询
      function searchInfo() {
        let values = {
          cardNum:searchRef.current.state.value
        }
        props.CustomerManagement.searchCustomerInfo(values).then((res)=>{
          if(res.code==200){
            console.log(res.data);
            setData(res.data)
            success(res.msg)
          }
        }).catch((err)=>{
          console.log(err);
          error(err.msg)
        })
      }
  // 渲染table
      const [selectionType, setSelectionType] = useState('checkbox');
      const [columns,setColumns] = useState([]);
      const [data,setData] = useState([]);
      function getList(){
        props.CustomerManagement.getCustomerInfoList().then((res)=>{
          let keys = Object.keys(res.data[0]);
          let cols = keys.map(item=>{
            if(item == 'sex'){
              return {
                  width: 140,
                  title: mapFieldToChinese[item],
                  dataIndex: item,
                  key: item,
                  align: 'center',
                  render: (val)=>{
                      if(val == 0){
                          return (
                              <span>男</span>
                          )
                      }else{
                          return (
                              <span>女</span>
                          )
                      }
                  }
              }
            }
            else if(item == 'memberType'){
              return {
                width: 140,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center',
                render: (val)=>{
                    if(val == 1){
                        return (
                            <span>银卡</span>
                        )
                    }else if(val == 2){
                        return (
                            <span>金卡</span>
                        )
                    }
                }
            }
            } 
            else if(item == 'birthday'){
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center',
                render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>
              }
            }
            else if(item == 'openCardDate'){
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center',
                render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>
              }
            }
            else{
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center'
              }
            }
          })
          cols.push({
            width:160,
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            fixed: 'right',
            render: ()=>{
                return(
                  <Space>
                  <Button shape="circle" type='primary' icon={<EditOutlined />} onClick={() => {setAdd(true);setAddEdit(1);}}></Button>
                  <Button className='upBtn' shape="circle" icon={<ArrowUpOutlined />} onClick={() => setUpgrade(true)}></Button>
                  <Button onClick={()=>{setDel(true)}} shape="circle" type='danger' icon={<DeleteOutlined />}></Button>
                </Space>
                )
            }
          })
          setColumns(cols)
          setData(res.data)
        }).catch((err)=>{
          console.log(err);
        }).finally(()=> {setLoading(false);})
      }
      
      useEffect(()=>{
        setLoading(true)
        getList();
      },[]);
    return (
        <Fragment>
            <Table 
            loading={loading}
            rowSelection={{
            type: selectionType,
                ...rowSelection,
            }} bordered='true' 
            title={() => {return (<Fragment>
              <h4>客户资料</h4>
              <div className='tableHeader'>
                <div>
                  <Input className='search' ref={searchRef} placeholder="请输入会员卡号" prefix={<SearchOutlined />}/>
                  <Button type='primary' onClick={searchInfo}>查询</Button>
                </div>
                <Button type='primary' onClick={() => {setAdd(true);setAddEdit(0)}}>新增会员</Button>
              </div>
              </Fragment>)}} 
            onRow = {(record) => {
              return {
                onClick: () => {
                  console.log(record);
                  setCardNum(record.memberCardNum)
                  setId(record.id)
                  }
                }
              }
            }
            columns={columns} dataSource={data} rowKey={(record) => `id${record.id}`} pagination={{ pageSize: 10 }} scroll={{ y: 400 }}></Table>

            {/* 会员升级 */}
            <Modal
              title="会员升级"
              centered
              visible={upgrade}
              okText= '确定'
              cancelText= '取消'
              onOk={() => {
                upGrad()
                setUpgrade(false);
              }}
              onCancel={() => setUpgrade(false)}
              width={400}
            >
              <div className='up'>
                <div>
                  会员卡号：<Input value={cardNum} disabled style={{ width: 170}} />
                </div>
                <div>
                  会员类型：<Select defaultValue={memberType} style={{ width: 170,textAlign:'left'}} onChange={vipTypeChange}>
                              <Option value="0">银卡会员</Option>
                              <Option value="1">金卡会员</Option>
                            </Select>
                </div>
                <div>
                  总积分：<Input ref={totalIntegralRef} style={{ width: 170}}/>
                </div>
              </div>
            </Modal>
            {/* 添加修改框 */}
            <Modal
              title="详细信息"
              centered
              visible={add}
              okText= '确定'
              cancelText= '取消'
              onOk={() => {
                setAdd(false);
                addEditInfo(addEdit)
              }}
              onCancel={() => {setAdd(false);clear()}}
              width={1000}
            >
              <div className='addModal'>
                <div>
                  会员卡号：<Input placeholder='请输入' ref={cardNumRef} />
                </div>
                <div>
                  客户名称：<Input placeholder='请输入' ref={memberNameRef} />
                </div>
                <div>
                  会员类型：<Select defaultValue={memberType} style={{ width: 170,textAlign:'left'}} onChange={vipTypeChange}>
                              <Option value="1">银卡会员</Option>
                              <Option value="2">金卡会员</Option>
                            </Select>
                </div>

                <div>
                  生日：<DatePicker placeholder='请选择日期' format={dateFormat} onChange={birthdayChange} style={{ width: 170}} />
                </div>
                <div>
                  联系电话：<Input placeholder='请输入' ref={phoneRef} />
                </div>
                <div>
                  性别：<Radio.Group onChange={sexChange} value={sex}>
                          <Radio value={0}>男</Radio>
                          <Radio value={1}>女</Radio>
                        </Radio.Group>
                </div>

                <div>
                  身份证号：<Input placeholder='请输入' ref={idNumRef} />
                </div>
                <div>
                  总积分：<Input placeholder='请输入' ref={totalIntegralRef} />
                </div>
                <div>
                  总消费金额(元)：<Input placeholder='请输入' ref={totalMonetaryRef} />
                </div>

                <div>
                  开卡门店：<Select defaultValue={openCardStore} style={{ width: 170,textAlign:'left'}} onChange={openCardStoreChange}>
                              <Option value="望京门店">望京门店</Option>
                              <Option value="王府井店">王府井店</Option>
                            </Select>
                </div>
                <div>
                  开卡日期：<DatePicker placeholder='请选择日期' format={dateFormat} onChange={openCardDateChange} style={{ width: 170}} />
                </div>
              </div>
            </Modal>
            {/* 删除提示 */}
            <Modal title="删除提示" 
            visible={del}
            okText= '确定'
            cancelText= '取消'
            onOk={() => {
              delInfo()
              setDel(false)
            }}
            onCancel={() => {setDel(false)}}
            >
              <p>你确定要删除这条信息吗</p>
            </Modal>
        </Fragment>
    );
}

export default inject('CustomerManagement')(observer(CustomerInfo))
// export default CustomerInfo;